package com.un.ebs.product.service.impl;

import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.un.ebs.core.config.OSSConfig;
import com.un.ebs.core.exception.BusinessEntityNotFoundException;
import com.un.ebs.core.exception.BusinessException;
import com.un.ebs.core.util.OSSUtil;
import com.un.ebs.core.util.SecurityUtils;
import com.un.ebs.core.util.StringUtils;
import com.un.ebs.product.domain.ProductSku;
import com.un.ebs.product.domain.SkuDocExt;
import com.un.ebs.product.mapper.ProductSkuDocMapper;
import com.un.ebs.product.domain.ProductSkuDoc;
import com.un.ebs.product.mapper.SkuDocExtMapper;
import com.un.ebs.product.service.ProductSkuDocService;
import com.un.ebs.product.service.ProductSkuService;
import net.sf.jsqlparser.expression.WindowRange;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.security.PrivateKey;
import java.util.Date;

/**
 * (ProductSkuDoc)表服务实现类
 *
 * @author liubo
 * @since 2020-11-18 13:55:14
 */
@Service("productSkuDocService")
public class ProductSkuDocServiceImpl extends ServiceImpl<ProductSkuDocMapper, ProductSkuDoc> implements ProductSkuDocService {

    @Resource
    private SkuDocExtMapper skuDocExtMapper;

    @Resource
    private ProductSkuService skuService;

    @Override
    public void uploadDesign(String docId, String skuId, String desc, MultipartFile file) {
        ProductSkuDoc obj;
        ProductSku sku = skuService.queryById(skuId);
        if (sku == null) {
            throw new BusinessEntityNotFoundException(skuId, "SKU");
        }

        if (!StringUtils.isNullOrEmpty(docId)) {
            obj = baseMapper.selectById(docId);
            if (obj == null) {
                throw new BusinessEntityNotFoundException(docId, "设计文件");
            }
            if (obj.getAuditStatus() || obj.getSubmitStatus()) {
                throw new BusinessException("设计文件已提交或审核，不能修改。");
            }
        } else {
            LambdaQueryWrapper<ProductSkuDoc> lq = Wrappers.lambdaQuery();
            lq.eq(ProductSkuDoc::getSkuId, skuId);
            lq.eq(ProductSkuDoc::getSubmitStatus, false);
            lq.eq(ProductSkuDoc::getIsDelete, false);
            if (baseMapper.selectCount(lq) > 0) {
                obj = baseMapper.selectOne(lq);
            } else {
                obj = new ProductSkuDoc();
                obj.setVersionCode(baseMapper.maxVersion(skuId));
                obj.setSkuId(skuId);
            }
        }
        String key = OSSUtil.upload(file, String.format("product_doc/%s/", skuId), String.format("%s_v%03d", sku.getSkuCode(), obj.getVersionCode()));
        obj.setDesignUrl(key);
        obj.setDesignDesc(desc);
        obj.setIsLastVersion(false);
        obj.insertOrUpdate();
    }

    @Override
    public void uploadRelease(String docId, String desc, MultipartFile file) {
        ProductSkuDoc obj = baseMapper.selectById(docId);
        if (obj == null) {
            throw new BusinessEntityNotFoundException(docId, "设计文件");
        }

        ProductSku sku = skuService.queryById(obj.getSkuId());
        if (sku == null) {
            throw new BusinessEntityNotFoundException(obj.getSkuId(), "SKU");
        }

        if (!StringUtils.isNullOrEmpty(docId)) {
            //替换OSS文件
            String key = OSSUtil.upload(file, String.format("product_doc/%s/", obj.getSkuId()), String.format("%s_release_v%03d", sku.getSkuCode(), obj.getVersionCode()));
            obj.setReleaseUrl(key);
            obj.setReleaseDesc(desc);
            obj.updateById();
        }
    }

    @Override
    public void submit(String id) {
        ProductSkuDoc obj = baseMapper.selectById(id);
        if (obj == null) {
            throw new BusinessEntityNotFoundException(id, "Doc");
        }
        if (obj.getSubmitStatus()) {
            throw new BusinessException("不能重复提交。");
        }

        obj.setSubmitAt(SecurityUtils.getUserContent().getId());
        obj.setSubmitAtName(SecurityUtils.getUserContent().getPersonnelName());
        obj.setSubmitStatus(true);
        obj.setSubmitTime(new Date());
        obj.updateById();
    }

    @Override
    public void submitCancel(String id) {
        ProductSkuDoc obj = baseMapper.selectById(id);
        if (obj == null) {
            throw new BusinessEntityNotFoundException(id, "Doc");
        }
        if (!obj.getSubmitStatus()) {
            return;
        }

        obj.setSubmitAt(null);
        obj.setSubmitAtName(null);
        obj.setSubmitStatus(false);
        obj.setSubmitTime(null);
        obj.updateById();
    }

    @Override
    public void audit(String id) {
        ProductSkuDoc obj = baseMapper.selectById(id);
        if (obj == null) {
            throw new BusinessEntityNotFoundException(id, "Doc");
        }
        if (!obj.getSubmitStatus()) {
            throw new BusinessException("文件未提交。");
        }
        if (obj.getAuditStatus()) {
            throw new BusinessException("不能重复审核。");
        }

        ProductSkuDoc updateDoc = new ProductSkuDoc();
        updateDoc.setIsLastVersion(false);
        baseMapper.update(updateDoc, new UpdateWrapper<ProductSkuDoc>().eq("sku_id", obj.getSkuId())
                .lt("version_code", obj.getVersionCode()));

        obj.setAuditAt(SecurityUtils.getUserContent().getId());
        obj.setAuditAtName(SecurityUtils.getUserContent().getPersonnelName());
        obj.setAuditStatus(true);
        obj.setAuditTime(new Date());
        obj.setIsLastVersion(true);
        obj.updateById();
    }

    @Override
    public void delete(String id) {
        ProductSkuDoc obj = baseMapper.selectById(id);
        if(obj==null){
            throw new BusinessEntityNotFoundException(id,"Doc");
        }
        if(obj.getSubmitStatus() || obj.getAuditStatus()){
            throw new BusinessException("文件已提交或已审核，不能删除。");
        }
        if(!StringUtils.isNullOrEmpty(obj.getDesignUrl())){
            OSSUtil.delete(obj.getDesignUrl());
        }
        if(!StringUtils.isNullOrEmpty(obj.getReleaseUrl())){
            OSSUtil.delete(obj.getReleaseUrl());
        }
        obj.deleteById();
    }

    @Override
    public IPage<SkuDocExt> query(String classId, String skuCode,int pageSize,int pageIndex) {
        Page<SkuDocExt> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<SkuDocExt> lq = Wrappers.lambdaQuery();
        if(!StringUtils.isNullOrEmpty(classId)){
            lq.eq(SkuDocExt::getClassId,classId);
        }
        if(!StringUtils.isNullOrEmpty(skuCode)){
            lq.like(SkuDocExt::getSkuCode,skuCode);
        }
        IPage<SkuDocExt> ret = skuDocExtMapper.selectPage(page,lq);
        for(SkuDocExt item : ret.getRecords()){
            if(!StringUtils.isNullOrEmpty(item.getDesignUrl())){
                item.setDesignUrl(OSSUtil.getObjectUrl(item.getDesignUrl()).toString());
            }
            if(!StringUtils.isNullOrEmpty(item.getReleaseUrl())){
                item.setReleaseUrl(OSSUtil.getObjectUrl(item.getReleaseUrl()).toString());
            }
        }
        return ret;
    }

    @Override
    public IPage<ProductSkuDoc> queryHistory(String skuId,int pageSize,int pageIndex) {
        Page<ProductSkuDoc> page = new Page<>(pageIndex,pageSize);
        LambdaQueryWrapper<ProductSkuDoc> lq = Wrappers.lambdaQuery();
        lq.eq(ProductSkuDoc::getSkuId,skuId);
        lq.orderByDesc(ProductSkuDoc::getVersionCode);
        IPage<ProductSkuDoc> ret = baseMapper.selectPage(page,lq);
        for(ProductSkuDoc item : ret.getRecords()){
            if(!StringUtils.isNullOrEmpty(item.getDesignUrl())){
                item.setDesignUrl(OSSUtil.getObjectUrl(item.getDesignUrl()).toString());
            }
            if(!StringUtils.isNullOrEmpty(item.getReleaseUrl())){
                item.setReleaseUrl(OSSUtil.getObjectUrl(item.getReleaseUrl()).toString());
            }
        }
        return ret;
    }
}